package com.zhangxiaofanfan.hotcode.second;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-30 08:25:58
 */
public class HotCode040 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        HotCode040 hotCode = new HotCode040();
        System.out.println(hotCode.diameterOfBinaryTree(root));

    }

    private Integer max = Integer.MIN_VALUE;
    private Map<TreeNode, Integer> map = new HashMap<>();
    public int diameterOfBinaryTree(TreeNode root) {
        dfs(root);
        return max;
    }

    public int dfs(TreeNode node) {
        if (node == null) {
            return 0;
        }
        if (map.containsKey(node)) {
            return map.get(node);
        }
        int left = dfs(node.left);
        int right = dfs(node.right);
        max = Math.max(max, left + right);
        map.put(node, Math.max(left, right) + 1);
        return map.get(node);
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
